<template>
	<movable-area class="chat-box-wrap w100 bg-white">
		<!-- <view class="group-members-wrap bg-white" v-if="isGroup">
			<scroll-view class="group-members relative" scroll-x="true" scroll-left="100%">
				<view class="wrap">
					<view class="member" v-for="(item, index) in groupMembers" :key="index">
						<image :src="item" class="avatar"></image>
					</view>
				</view>
			</scroll-view>
		</view> -->

		<movable-view :x="x" :y="y" class="group-info-wrap" direction="all" v-if="currentConversationType === 'GROUP'">
			<image class="group-info" src="/static/images/group_info.png" @click="handleToDetail"></image>
		</movable-view>
		<view class="occupying-top"></view>
		<view class="chat-box">
			<view :class="{'msg-item': true, 'item-left': message.flow === 'in', 'item-right': message.flow === 'out'}" v-for="(message, index) in currentMessageList"
			 :key="index">
				<!--系统消息-->
				<!-- <view class="notice" v-if="message.type === 'TIMGroupTipElem' || message.type === 'TIMGroupSystemNoticeElem'">
					<view class="content">
						<text v-for="(view, index1) in message.virtualDom" :key="index1">
							<text v-if="view.name === 'groupTip' || 'system'">{{view.text}}</text>
						</text>
					</view>
				</view> -->
				<view v-if="message.isRevoked" :key="message.ID">
					<view class="notice">
						<view class="content">
							<template v-if="message.from === myTimInfo.userID">你撤回了一条消息</template>
							<template v-else>{{message.from}}撤回了一条消息</template>
						</view>
						<template v-if="message.from === myTimInfo.userID">
							<view v-if="(currentTime - message.time < 120) && message.type === 'TIMTextElem'" @click="reEdit(message)" class="re-edit">重新编辑</view>
						</template>
					</view>
				</view>
				<!--非系统消息-->
				<view class="other-msg">
					<view class="header inline" @click="handleChat(message)" hover-class="none">
						<!-- 自己发的消息头像 -->
						<image class="avatar" v-if="message.flow === 'out'" :src="myTimInfo.avatar" />
						<!-- 收到的消息头像 -->
						<image class="avatar" v-else-if="currentConversation.type === 'C2C'" :src="currentConversation.userProfile.avatar" />
						<image class="avatar" v-else :src="message.avatar || '/static/images/head.png'" />
					</view>
					<view class="info relative">
						<text class="name">
							<template v-if="currentConversation.type === 'C2C'">
								<template v-if="message.flow === 'in'">
									{{currentConversation.userProfile.nick || currentConversation.userProfile.userID}}
								</template>
								<template v-else>
									{{myTimInfo.nick || myTimInfo.userID}}
								</template>
							</template>
							<template v-else>
								{{message.nameCard || message.nick || myTimInfo.nick || message.from}}
							</template>
						</text>
						<!-- 文字消息 -->
						<view class="text relative" v-if="message.type === 'TIMTextElem'" @longpress="handleMessage(message)">
							<view class="load" @click="handleResend(message)" v-if="message.from === myTimInfo.userID">
								<view :class="message.status"></view>
							</view>
							<view class="message">
								<view class="text-message">
									<view v-for="(view, index2) in message.virtualDom" :key="index2">
										<text v-if="view.name === 'span'">{{view.text}}</text>
										<image v-if="view.name === 'img'" :src="view.src" style="width:20px;height:20px;" />
									</view>
								</view>
								<text class="triangle"></text>
							</view>
						</view>
						<!-- 自定义消息 -->
						<view class="text relative" v-else-if="message.type === 'TIMCustomElem'" @longpress="handleMessage(message)">
							<view class="load" @click="handleResend(message)" v-if="message.from === myTimInfo.userID">
								<view :class="message.status"></view>
							</view>
							<view class="message">
								<view class="text-message">
									<text>创建组局成功，请等待审核通过</text>
								</view>
								<text class="triangle"></text>
							</view>
						</view>
						<!-- 系统消息 -->
						<view class="text relative" v-else-if="message.type === 'TIMGroupTipElem'" @longpress="handleMessage(message)">
							<view class="message">
								<text v-for="(view, index1) in message.virtualDom" :key="index1">
									<text v-if="view.name === 'groupTip' || 'system'">群公告已更新</text>
								</text>
								<text class="triangle"></text>
							</view>
						</view>
						<!-- 图片消息 -->
						<view class="image relative" v-else-if="message.type === 'TIMImageElem'" @longpress="handleMessage(message)"
						 style="margin-top: 65rpx;">
							<view class="load" @click="handleResend(message)" v-if="message.from === myTimInfo.userID">
								<view :class="message.status"></view>
							</view>
							<image class="image-message" :src="message.payload.imageInfoArray[1].url" mode='widthFix' @click="previewImage(message.payload.imageInfoArray[1].url)" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="occupying-bottom" :style="{ height: '200rpx' }"></view>
		<view class="send-box">
			<view class="exhibition-wrap w100" id="exhibitionWrap">
				<view class="tips">
					<view class="tips-text">参与者应自行确定活动真实性，并时刻确保自身安全，谨防上当受骗；参与者不得参与触犯法律法规和道德底线的活动；参与者自愿承担参加活动带来的一切后果。</view>
				</view>
				<view :class="{'exhibition-box w100 flex-x-around': true, 'border': showFileBox}">
					<view class="input flex-x-between bg-white">
						<input class="w100 textarea" placeholder="请输入回复内容..." v-model="messageContent" maxlength="3000" @focus="isFocus = true"
						 @blur="isFocus = false" cursor-spacing="20"></input>
						<!--  <textarea placeholder="请输入回复内容" class="w100 textarea" auto-height fixed="true"
						 maxlength="3000" cursor-spacing="20" :show-confirm-bar="false" v-model="messageContent" confirm-type="send"
						 @focus="isFocus = true" @blur="isFocus = false"></textarea>  -->
					</view>
					<text class="iconfontPT iconbiaoqing smail-icon" @click="handleEmoji()"></text>
					<text v-if="!messageContent.length" class="iconfontPT icondakai file-icon" @click="handleMore()"></text>
					<text v-else class="send-btn" @click='sendMessage'>发送</text>
				</view>
				<!--    emoji部分-->
				<view class="bottom-emoji" v-if="isEmojiOpen">
					<view class="emojis">
						<view v-for="(emojiItem, index3) in emojiName" class="emoji" :key="index3" @click="chooseEmoji(emojiItem)">
							<image :src="emojiUrl + emojiMap[emojiItem]" style="width:100%;height:100%" />
						</view>
					</view>
				</view>
				<!--    更多部分-->
				<view class="bottom-image" v-if="isMoreOpen">
					<view class="images">
						<view class="block" @click="sendPhoto('camera')">
							<view class="image">
								<text class="iconfontPT iconpaizhaoshangchuan"></text>
							</view>
							<view class="name">
								拍摄
							</view>
						</view>
						<view class="block" @click="sendPhoto('album')">
							<view class="image">
								<text class="iconfontPT icontupian01"></text>
							</view>
							<view class="name">
								图片
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		</view>
	</movable-area>
</template>

<script>
	import TIM from '../../../utils/tim-wx.js';
	import {
		emojiName,
		emojiMap,
		emojiUrl
	} from '../../../utils/emoji-map'

	import {
		userOpt,
		optionsId,
		recordOptions
	} from '../../../setting.js'
	import {
		mapGetters
	} from "vuex";

	const audioContext = uni.createInnerAudioContext(),
		recorderManager = uni.getRecorderManager()

	export default {
		data() {
			return {
				x: '650rpx',
				y: '40rpx',
				messageContent: '',
				conversation: {},
				messageKey: '',
				lastMsgTime: '',
				count: 15,
				isEmojiOpen: false,
				isMoreOpen: false,
				isFocus: false,
				isGroup: false,
				messageList: [],
				emojiName: emojiName,
				emojiMap: emojiMap,
				emojiUrl: emojiUrl,
				height: 0,
				downloadInfo: {},
				safeBottom: 34,
				isRecord: false,
				canSend: true,
				startPoint: 0,
				title: '正在录音',
				isShow: false,
				revokeModal: false,
				revokeMessage: {},
				currentTime: 0,
				currentTimeID: '',
				oid:''
			}
		},
		onShow() {
			this.isShow = true
			const that = this
			this.currentTimeID = setInterval(() => {
				that.currentTime = new Date().getTime() / 1000
			}, 3000)
		},
		onLoad(options) {
			this.oid = options.oid
			this.set = options.toAccount
			// 设置header——聊天对象昵称或群名
			uni.setNavigationBarTitle({
				title: this.set
			})

			let query = uni.createSelectorQuery()
			let that = this
			uni.$Tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, () => {
				query.select('#chat').boundingClientRect((res) => {
					if (res && res.bottom - that.height < 150) {
						that.scrollToBottom()
					}
				}).exec()
			})
			let interval = setInterval(() => {
				if (this.currentMessageList.length !== 0) {
					this.scrollToBottom()
					clearInterval(interval)
				}
			}, 1500)
		},
		// 退出聊天页面的时候所有状态清空
		onUnload() {
			clearInterval(this.currentTimeID)
			uni.$Tim.setMessageRead({
				conversationID: this.currentConversationID
			})
			this.isEmojiOpen = false
			this.isMoreOpen = false
			this.messageContent = ''
			this.isShow = false
		},
		onPullDownRefresh() {
			this.$throttle(this.getMessageList, 1000)
		},
		computed: {
			...mapGetters(['currentMessageList', 'currentConversation', 'myTimInfo', 'toAccount',
				'currentConversationType', 'currentConversationID'
			])
		},
		methods: {
			handleChat(e) {
				const operatorID = e.from,
					flow = e.flow,
					type = e.type,
					conversationType = e.conversationType;

				if (flow !== 'in') return
				if (type == 'TIMGroupTipElem') return
				if (conversationType == 'C2C') return

				let params = {
					url: '/pages/life-circle/chat-box/index',
					conversationID: `C2C${ operatorID }`
				};
				this.$store.dispatch('tim/checkoutConversation', params)
			},
			handleToDetail() {
				uni.navigateTo({
					url: `/pages/life-circle/group-chat-info/index?oid=${this.oid}`
				})
			},
			chooseRecord() {
				this.isRecord = !this.isRecord
			},
			// 手指离开页面滑动
			handleTouchEnd() {
				uni.hideLoading()
				recorderManager.stop()
			},
			// 滚动到列表bottom
			scrollToBottom() {
				if (this.isShow) {
					uni.pageScrollTo({
						scrollTop: 99999
					})
				}
			},
			// 失去焦点
			loseFocus() {
				this.handleClose()
			},
			// // 群简介或者人简介
			// toDetail({
			// 	userID
			// }) {
			// 	const params = {
			// 		url: '/pages/life-circle/chat-box/index',
			// 		conversationID: `C2C${userID}_group`
			// 	}
			// 	this.$store.dispatch('tim/checkoutConversation', params)
			// },
			// 获取消息
			getMessageList() {
				this.$store.dispatch('tim/getMessageList')
				uni.stopPullDownRefresh()
			},
			// 处理emoji选项卡
			handleEmoji() {
				if (this.isFocus) {
					this.isFocus = false
					this.isEmojiOpen = true
				} else {
					this.isEmojiOpen = !this.isEmojiOpen
					this.isMoreOpen = false
				}
			},
			// 处理更多选项卡
			handleMore() {
				if (this.isFocus) {
					this.isFocus = false
					this.isMoreOpen = true
				} else {
					this.isMoreOpen = !this.isMoreOpen
					this.isEmojiOpen = false
				}
			},
			// 选项卡关闭
			handleClose() {
				// this.rateModal = false
				this.isFocus = false
				this.isMoreOpen = false
				this.isEmojiOpen = false
			},
			isnull(content) {
				if (content === '') {
					return true
				}
				const reg = '^[ ]+$'
				const re = new RegExp(reg)
				return re.test(content)
			},
			// 发送text message 包含 emoji
			sendMessage() {
				let _this = this
				if (!this.isnull(this.messageContent)) {
					const message = uni.$Tim.createTextMessage({
						to: _this.toAccount,
						conversationType: _this.currentConversationType,
						payload: {
							text: _this.messageContent
						}
					})

					let index = this.currentMessageList.length
					this.$store.commit('tim/SEND_MESSAGE', message)
					uni.$Tim.sendMessage(message)
					this.messageContent = ''
				} else {
					this.$store.commit('tim/SEND_MESSAGE', {
						title: '消息不能为空'
					})
				}
				this.isFocus = false
				this.isEmojiOpen = false
				this.isMoreOpen = false
			},
			sendPhoto(name) {
				let self = this
				if (name === 'album') {
					this.chooseImage(name)
				} else if (name === 'camera') {
					uni.getSetting({
						success: function(res) {
							if (!res.authSetting['scope.camera']) { // 无权限，跳转设置权限页面
								uni.authorize({
									scope: 'scope.camera',
									success: function() {
										self.chooseImage(name)
									}
								})
							} else {
								self.chooseImage(name)
							}
						}
					})
				}
			},
			chooseImage(name) {
				let _this = this
				let message = {}
				uni.chooseImage({
					sourceType: [name],
					count: 1,
					success: function(res) {
						message = uni.$Tim.createImageMessage({
							to: _this.toAccount,
							conversationType: _this.currentConversationType,
							payload: {
								file: res
							},
							onProgress: percent => {
								_this.percent = percent
							}
						})
						_this.$store.commit('tim/SEND_MESSAGE', message)
						uni.$Tim.sendMessage(message).then(() => {
							_this.percent = 0
						}).catch((err) => {
							console.log(err)
						})
					}
				})
				this.handleClose()
			},
			previewImage(src) {
				uni.previewImage({
					current: src, // 当前显示图片的http链接
					urls: [src]
				})
			},
			// 发消息选中emoji
			chooseEmoji(item) {
				this.messageContent += item
			},
			// 重发消息
			handleResend(message) {
				if (message.status === 'fail') {
					uni.$Tim.resendMessage(message)
				}
			},
			// 播放音频
			openAudio(audio) {
				let that = this
				audioContext.src = audio.url
				audioContext.play()
				audioContext.onPlay(() => {})
				audioContext.onEnded(() => {
					uni.hideToast()
				})
				audioContext.onError(() => {
					that.$store.commit('tim/SHOW_TOAST', {
						title: '小程序暂不支持播放该音频格式',
						icon: 'none',
						duration: 2000
					})
				})
			},
			getRandomInt(min, max) {
				min = Math.ceil(min)
				max = Math.floor(max)
				return Math.floor(Math.random() * (max - min)) + min
			},
			// 长按消息触发是否撤回
			handleMessage(message) {
				if (message.from === this.myTimInfo.userID) {
					const revokeTimeout = 2 * 60 * 1000
					const now = new Date().getTime()
					if (now - message.time * 1000 < revokeTimeout) {
						this.revokeModal = true
						this.revokeMessage = message
					}
				}
			},
			// 撤回消息
			handleRevokeMessage() {
				uni.$Tim.revokeMessage(this.revokeMessage).then(res => {
					this.revokeModal = false
					this.$store.commit('tim/SHOW_TOAST', {
						title: '撤回成功',
						duration: 500
					})
				})
			},
			// 撤回后时间限制内，重新编辑
			reEdit(message) {
				this.messageContent = message.payload.text
			}
		}
	}
</script>

<style lang="less">
	.chat-box-wrap {
		background: #f8f8f8;
		display: table;
		height: 100vh;

		.group-info-wrap {
			z-index: 11111;
			position: fixed;

			.group-info {
				width: 40rpx;
				height: 40rpx;
				padding: 14rpx;
				box-shadow: 0 0 8rpx #808080;
				background-color: #ededed;
				border-radius: 50%;
			}
		}

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 100%;
		}

		.occupying-top {
			height: 120rpx;
		}

		.occupying-bottom {
			height: 220rpx;
		}

		.group-members-wrap {
			padding: 15rpx 0;
			box-shadow: 0rpx 5rpx 25rpx 2rpx rgba(153, 153, 153, 0.15);
			position: fixed;
			top: 0;
			left: 0;
			z-index: 111;

			.group-members {

				// white-space: nowrap;
				&::after {
					position: absolute;
					left: 50%;
					top: 123rpx;
					-webkit-transform: translate(-50%, -50%);
					transform: translate(-50%, -50%);
					content: '';
					display: inline-block;
					width: 240rpx;
					height: 40rpx;
					background: url();
					background-size: contain;
				}

				.wrap {
					position: relative;
					left: 0;
					white-space: nowrap;
					width: 100vw;
				}

				.member {
					display: inline-block;
					margin: 0 25rpx;
				}
			}
		}

		.chat-box {
			padding: 45rpx 30rpx 60rpx;

			.msg-item {
				margin-bottom: 100rpx;

				&.item-right {

					.header {
						text-align: right;

						.avatar {
							float: right;
						}
					}

					.name {
						right: 0;
					}

					.info {
						justify-content: flex-end;

						.text {
							background: #e41805FF;
							color: #ffffff;
							box-shadow: 0rpx 60rpx 30rpx -45rpx rgba(228, 24, 5, .5);

							.triangle {
								right: -18rpx;
								border-top: -5rpx solid transparent;
								border-bottom: 16rpx solid transparent;
								border-left: 10px solid #e41805FF;
								top: 25rpx;
							}
						}
					}

				}

				&.item-left {
					// display: flex;
					// flex-direction: space-between;
					// align-items: top;
					// flex-wrap: wrap;
					// justify-content: row;

					.other-msg {
						display: flex;
						flex-direction: row;
						align-items: center;
						flex-wrap: wrap;
						justify-content: flex-start;
					}

					.header {
						text-align: left;
						margin-right: 10rpx;

						.avatar {
							float: left;
						}
					}

					.name {
						left: 0;
					}

					.info {
						// justify-content: flex-start;

						.text {
							background: #ffffff;
							color: #000000;
							.triangle {
								left: -9px;
								border-top: -5rpx solid transparent;
								border-bottom: 15rpx solid transparent;
								border-right: 20rpx solid #ffffff;
								top: 25rpx;
							}
						}
					}
				}

				.header {
					height: 70rpx;
				}

				.info {
					width: calc(100vw - 150rpx);
					display: flex;
					flex-direction: row;
					align-items: center;

					.name {
						font-size: 24rpx;
						font-weight: 400;
						color: rgba(103, 103, 103, 1);
						position: absolute;
						top: 0;
					}

					.text {
						max-width: calc(100vw - 230rpx);
						border-radius: 10rpx;
						display: inline-block;
						padding: 15rpx 30rpx;
						vertical-align: top;
						position: relative;
						font-size: 36rpx;
						word-break: break-all;
						background: #e41805FF;
						color: #ffffff;
						margin-top: 15rpx;
						top: 45rpx;

						.triangle {
							width: 0;
							height: 0;
							position: absolute;
						}
					}

					.image {
						.image-message {
							max-width: 360rpx;
						}
					}
				}

			}
		}

		.send-box {
			.exhibition-wrap {
				box-shadow: 0rpx -2rpx 8rpx 0rpx rgba(0, 0, 0, 0.1);
				position: fixed;
				bottom: 0%;
				right: 0;
				z-index: 1112;
				padding-bottom: 25px;
				box-sizing: border-box;
				background: rgba(245, 245, 245, 1);
				.tips{
					overflow: hidden;
					margin: 0 20rpx;
				}
				.tips-text{
					font-size: 24rpx;
					color: #999999;
					white-space:nowrap;
					animation: shiftLeft linear 30s infinite;
				}
				.exhibition-box {
					margin-top: 20rpx;
					padding-bottom: 15rpx;
					&.border {
						border-bottom: 1rpx solid rgba(203, 203, 203, .5);
					}

					

					.send-btn {
						background: #E41805FF;
						color: #ffffff;
						border-radius: 10rpx;
						font-size: 26rpx;
						padding: 10rpx 30rpx;
					}

					.input {
						padding: 0 15px;
						box-sizing: border-box;
						border-radius: 50rpx;
						width: 465rpx;
						min-height: 78rpx;
						max-height: 150rpx;

						.textarea {

							max-height: 150rpx;
						}

						.smail-icon {
							font-size: 54rpx;
							margin-right: 20rpx;
						}
					}

					.smail-icon,
					.file-icon {
						font-size: 52rpx;
						color: #666666;
					}
				}

				.bottom-emoji {
					position: relative;

					.emojis {
						height: 300rpx;
						display: flex;
						flex-direction: row;
						flex-wrap: wrap;
						overflow-y: scroll;
						box-sizing: border-box;

						.emoji {
							height: 12.5vw;
							width: 12.5vw;
							padding: 16rpx;
							box-sizing: border-box;
						}
					}
				}

				.bottom-image {
					box-sizing: border-box;

					.images {
						box-sizing: border-box;
						display: flex;
						padding: 0 24rpx;
						margin-top: 32rpx;

						.block {
							box-sizing: border-box;
							display: flex;
							flex-direction: column;
							justify-content: center;
							align-items: center;
							margin: 0 24rpx;

							.name {
								margin-top: 12rpx;
								font-size: 24rpx;
								color: #999;
								text-align: center;
							}

							.image {
								width: 128rpx;
								height: 128rpx;
								display: flex;
								justify-content: center;
								align-items: center;
								box-sizing: border-box;
								border-radius: 16rpx;
								background-color: #fff;
								padding: 3vw;

								.iconfontPT {
									font-size: 48rpx;
								}
							}
						}

						&:last-child {
							margin-bottom: 32rpx;
						}
					}
				}
			}
		}
	}
	
	@keyframes shiftLeft
	{
		from {
			transform: translateX(100%);
		}
		to{
			transform: translateX(-300%);
		}
	}
</style>
